﻿
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace RWXMLEdit.Common
{
    public static class RwHasher
    {
        public static byte[] ConvertStringToByteArray(string data)
        {
            return(new UnicodeEncoding()).GetBytes(data);
        }

        public static string GetSha1Hash(string pathName)
        {
            string strResult;
            FileStream oFileStream = null;
            var oSha1Hasher = new SHA1CryptoServiceProvider();

            try
            {
                oFileStream = GetFileStream(pathName);

                byte[] arrbytHashValue = oSha1Hasher.ComputeHash(oFileStream);               

                string strHashData = BitConverter.ToString(arrbytHashValue);

                strHashData = strHashData.Replace("-", "");

                strResult = strHashData;
            }
            catch (Exception ex)
            {
                throw new HashException(ex.Message, pathName);
            }
            finally
            {
                if (oFileStream != null)
                {
                    oFileStream.Close();
                }
            }

            return (strResult);
        }

        public static string GetMd5Hash(string pathName)
        {
            string strResult;
            FileStream oFileStream = null;

            var oMd5Hasher = new MD5CryptoServiceProvider();

            try
            {
                oFileStream = GetFileStream(pathName);

                byte[] arrbytHashValue = oMd5Hasher.ComputeHash(oFileStream);                

                string strHashData = BitConverter.ToString(arrbytHashValue);

                strHashData = strHashData.Replace("-", "");

                strResult = strHashData;
            }
            catch (Exception ex)
            {
                throw new HashException(ex.Message, pathName);
            }
            finally
            {
                if(oFileStream != null)
                    oFileStream.Close();
            }


            return (strResult);
        }

        private static FileStream GetFileStream(string pathName)
        {
            return(new FileStream(pathName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
        }
    }
}
